<?php
	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/database.php';
	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/profile.php';

	//Ensure it's the logged in user
	if ($user['id'] != $_SESSION['user']) {
		header("Location:http://" . $_SERVER['HTTP_HOST'] . '/deviantpic/index.php');
		die();
	}

	//Prepare array
	$all_threads		= array();
	$unique_threads		= array();
	$message_threads = array();

	//Get list of thread
	$result = mysql_query("SELECT thread FROM messages WHERE sender_id=" . $_SESSION['user'] . " ORDER BY time DESC") or die(mysql_error());
	$row	= mysql_fetch_array($result);
	while ($row) {
		//Add to thread list
		$all_threads[]	= $row['thread'];
		$row			= mysql_fetch_array($result);
	}

	//Get messages aimed at user
	$result = mysql_query("SELECT message_id FROM message_receivers WHERE receiver_id=" . $_SESSION['user']) or die(mysql_error());
	$row	= mysql_fetch_array($result);
	
	while ($row) {
		//Get message thread id
		$message_result = mysql_query("SELECT thread FROM messages WHERE id=" . $row['message_id']) or die(mysql_error());
		$thread_data	= mysql_fetch_array($message_result);

		//Add to thread list
		$all_threads[]	= $thread_data['thread'];

		//Next
		$row = mysql_fetch_array($result);
	}

	//Get unique threads
	$unique_threads = array_unique($all_threads);
	
	//sort($unique_threads);
	//$unique_threads = array_reverse($unique_threads);

	//Get pages
	$page = 1;
	if (isset($_GET['page'])) $page = $_GET['page'];	
	
	$pages = ceil(count($unique_threads)/$messages_in_page);
	$index = $messages_in_page * ($page - 1);
	$index_max = $index + $messages_in_page;
	
	//For thread until amount
	$i = -1;
	foreach ($unique_threads as $unique_thread) {
		$i++;
		
		//Prepare
		if ($i==$index) {
			$index++;
			if ($index>$index_max) break;
		} else {
			continue;
		}
			
		$messages	= array();

		//Get message
		$result = mysql_query("SELECT * FROM messages WHERE thread=" . $unique_thread) or die(mysql_error());
		$row	= mysql_fetch_array($result);
		
		$comment_index = 0;
		$comment_max = $replies_in_message + 1;

		//While there's still message
		while ($row && count($messages) < $comment_max) {
			//Get sender name
			$sender_result		= mysql_query("SELECT username FROM users WHERE id=" . $row['sender_id']) or die(mysql_error());
			$sender_row			= mysql_fetch_array($sender_result);
			$row['sender']		= $sender_row['username'];
			$row['receivers']	= array();

			//Get receivetrs
			$receivers_result	= mysql_query("SELECT receiver_id FROM message_receivers WHERE message_id=" . $row['id']);
			$receivers_row		= mysql_fetch_array($receivers_result);
			while ($receivers_row) {
				//Get name
				$receiver_result	= mysql_query("SELECT username FROM users WHERE id=" . $receivers_row['receiver_id']);
				$receiver_row		= mysql_fetch_array($receiver_result);
				$row['receivers'][]	= $receiver_row['username'];

				//Next
				$receivers_row = mysql_fetch_array($receivers_result);
			}

			//Insert to message list
			$messages[] = $row;

			//Next
			$row = mysql_fetch_array($result);
		}

		//Add to message thread
		$message_threads[] = array('messages'=>$messages);
	}

	require_once $_SERVER['DOCUMENT_ROOT'] . '/deviantpic/inc/doctype.php';
?>

			<!-- Inbox -->
			<div id="inbox-messages">
				<div class="tabs-title" id="inbox-title">
					<span class="title">Inbox</span>
					<span class="new-message">
						<?php echo "<a " . create_anchor ("message", null) . ">new message</a>"; ?>
					</span>
				</div>

				<ul id="inbox-messages">
					<?php
						//For each thread
						foreach ($message_threads as $message_thread) {
							$i = 0;
					?>
					<li class="message-thread">
						<!-- Message thread -->
						<div class="message-thread">
							<!-- First message -->
							<div class="message-thread-head">
								<div class="message">
									<!-- Header: subject & time -->
									<div class="message-header">
										<div class="message-header-subject"><?php echo $message_thread['messages'][$i]['subject']; ?></div>
										<div class="message-header-time"><?php echo $message_thread['messages'][$i]['time']; ?></div>
									</div>

									<!-- Content -->
									<div class="message-content">
										<!-- Sender -->
										<div class="message-content-sender">
											<span class="message-from">From: </span>
											<span class="message-sender"><?php echo $message_thread['messages'][$i]['sender']; ?></span>;
										</div>

										<!-- Receivers -->
										<div class="message-content-receiver">
											<span class="message-to">To: </span>
											<span class="message-receivers">
												<?php
													foreach($message_thread['messages'][$i]['receivers'] as $receiver) {
												?>
												<span class="message-receiver"><?php echo $receiver; ?></span>;
												<?php
													}
												?>
											</span>
										</div>

										<!-- Content -->
										<div class="message-content-text">
											<span class="message-content-text"><?php echo $message_thread['messages'][$i]['content']; ?></span>
											<span class="message-reply">
												<a href= <?php echo '"message.php?id=' . $_SESSION['user'] . "&reply=" . $message_thread['messages'][$i]['id'] . '"'; ?>>reply</a>
											</span>
										</div>
									</div>
								</div>
							</div>

							<!-- The rest -->
							<div class="message-thread-tail">
								<ul id=<?php echo "message-tail-".$message_thread['messages'][$i]['id']."" ?> class="message-thread-tail">
									<?php
										echo "<a href=\"javascript:getReplies(".$user['id'].",".$message_thread['messages'][$i]['id'].");\"><b>[View All Replies]</b></a>&nbsp;&nbsp;&nbsp;\n";
										
										//From 1 to the rest
										$i = 1;
										while ($i < count($message_thread['messages'])) {
									?>
									<li class="message">
										<div class="message">
											<!-- Header: subject & time -->
											<div class="message-header">
												<div class="message-header-subject"><?php echo $message_thread['messages'][$i]['subject']; ?></div>
												<div class="message-header-time"><?php echo $message_thread['messages'][$i]['time']; ?></div>
											</div>

											<!-- Content -->
											<div class="message-content">
												<!-- Sender -->
												<div class="message-content-sender">
													<span class="message-from">From: </span>
													<span class="message-sender"><?php echo $message_thread['messages'][$i]['sender']; ?></span>;
												</div>

												<!-- Receivers -->
												<div class="message-content-receiver">
													<span class="message-to">To: </span>
													<span class="message-receivers">
														<?php
															foreach($message_thread['messages'][$i]['receivers'] as $receiver) {
														?>
														<span class="message-receiver"><?php echo $receiver; ?></span>;
														<?php
															}
														?>
													</span>
												</div>

												<!-- Content -->
												<div class="message-content-text">
													<span class="message-content-text"><?php echo $message_thread['messages'][$i]['content']; ?></span>
													<span class="message-reply">
														<a href= <?php echo '"message.php?id=' . $_SESSION['user'] . "&reply=" . $message_thread['messages'][$i]['id'] . '"'; ?>>reply</a>
													</span>
												</div>
											</div>
										</div>
									</li>
									<?php
										//Next
										$i++;
										}
									?>
								</ul>
							</div>
						</div>
					</li>
					<?php
						}
					?>
				</ul>
				
				<!-- Page Navigation -->
				<?php 
				$page_now=1;
			    while($pages) {
			        if ($page_now==$page) {
			            echo "<a href=\"javascript:goto_message_page(".$page_now.",".$user['id'].");\"><b>[".$page_now."]</b></a>&nbsp;&nbsp;&nbsp;\n";
			        } else {
			            echo "<a href=\"javascript:goto_message_page(".$page_now.",".$user['id'].");\">".$page_now."</a>&nbsp;&nbsp;&nbsp;\n";
			        }
			        $pages--;
			        $page_now++;
			    }
				?>
			</div>